package bTree.LeetCode;

import javax.swing.tree.TreeNode;
import java.util.*;

public class 二叉树的层序遍历II {
    List<List<Integer>>res=new ArrayList<>();
    public List<List<Integer>> levelOrderBottom(TreeNode root) {
        if(root==null){
            return res;
        }
        bfs(root);
        Collections.reverse(res);
        return res;
    }

    private void bfs(TreeNode root) {
        Queue<TreeNode>queue=new LinkedList<TreeNode>();
        queue.add(root);
        while (!queue.isEmpty()){
            int len=queue.size();
            List<Integer>path=new ArrayList<>();
            for(int i=0;i<len;i++){
                TreeNode peek = queue.peek();
                if(peek.left!=null){
                    queue.add(peek.left);
                }
                if(peek.right!=null){
                    queue.add(peek.right);
                }
                path.add(peek.val);
                queue.poll();
            }
            res.add(path);
        }
    }
}